<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>商品管理</title>
	<script src="js/jquery-3.7.1.js"></script>
	<style>
		.head {
			padding: 5px;
			border: #80ffff solid;
		}

		table {
			width: 100%;
			border-collapse: collapse;
		}

		table,
		th,
		td {
			border: 1px solid black;
		}

		th,
		td {
			padding: 10px;
			text-align: center;
		}

		.form-container {
			position: relative;
			float: left;
			border: 1px solid red;
			padding: 20px;
			margin-top: 40px;
			width: 300px;
			background-color: #f9f9f9;
			border-radius: 10px;
		}

		.form-div {
			position: absolute;
			top: -15px;
			left: 15%;
			transform: translateX(-50%);
			background-color: #000000;
			color: #ffffff;
			padding: 5px;
			font-weight: bold;
			text-align: center;
			width: 80px;
		}

		.highlight {
			width: 200px;
			height: 50px;
			text-align: center;
			float: left;
			margin: 20px;
			margin-top: 40px;
			padding-top: 20px;
			background-color: yellow;
			font-weight: bold;
		}
	</style>
</head>
<body>
<div class="head">
	<!-- 商品列表表格 -->
	<table>
		<thead>
		<tr>
			<th><input type="checkbox" id="selectAll"> 全选</th>
			<th>商品编号</th>
			<th>名称</th>
			<th>价格</th>
			<th>上架日期</th>
			<th>是否下架</th>
			<th>操作</th>
		</tr>
		</thead>
		<tbody id="productTableBody">

		</tbody>
	</table>

	<!-- 添加商品表单 -->
	<div class="form-container">
		<div class="form-div">商品添加</div>
		<form id="addProductForm">
			<label>商品编号：</label>
			<input type="text" id="id" required><br><br>

			<label>商品名称：</label>
			<input type="text" id="name" required><br><br>

			<label>商品价格：</label>
			<input type="text" id="price" required><br><br>

			<label>上架日期：</label>
			<select id="year">
				<option>2018</option>
				<option>2019</option>
				<option>2020</option>
				<option>2021</option>
				<option>2022</option>
				<option>2023</option>
				<option>2024</option>
			</select>年
			<select id="month">
				<option>01</option>
				<option>02</option>
				<option>03</option>
				<option>04</option>
				<option>05</option>
				<option>06</option>
				<option>07</option>
				<option>08</option>
				<option>09</option>
				<option>10</option>
				<option>11</option>
				<option>12</option>
			</select>月
			<select id="day">
				<option>01</option>
				<option>02</option>
				<option>03</option>
				<option>04</option>
				<option>05</option>
				<option>06</option>
				<option>07</option>
				<option>08</option>
				<option>09</option>
				<option>10</option>
				<option>11</option>
				<option>12</option>
				<option>13</option>
				<option>14</option>
				<option>15</option>
				<option>16</option>
				<option>17</option>
				<option>18</option>
				<option>19</option>
				<option>20</option>
				<option>21</option>
				<option>22</option>
				<option>23</option>
				<option>24</option>
				<option>25</option>
				<option>26</option>
				<option>27</option>
				<option>28</option>
				<option>29</option>
				<option>30</option>
				<option>31</option>
			</select>日
			<br><br>

			<label>是否下架：</label>
			<input type="radio" name="off-shelf" value="yes" checked> 是
			<input type="radio" name="off-shelf" value="no"> 否
			<br><br>

			<button type="button" id="btnAdd">添加商品</button>
			<button type="button" id="btnSave" style="display: none;">保存修改</button>
			<button type="button" id="btnDel">批量删除</button>
			<button type="button" id="btnCloseDetails" style="display: none;">关闭详情</button>

		</form>
	</div>
	<div class="highlight">双击表单，添加数据</div>
</div>

<script>
	// 阻止表单默认提交
	$("button").click(function(event) {
		event.preventDefault();
	});
	// 全选/取消全选
	$("#selectAll").click(function() {
		$(".itemCheckbox").prop("checked", this.checked);
	});

	// 单选
	$(".itemCheckbox").click(function() {
		if ($(".itemCheckbox:checked").length == $(".itemCheckbox").length) {
			$("#selectAll").prop("checked", true);
		} else {
			$("#selectAll").prop("checked", false);
		}
	});

	// 获取商品数据并渲染
	$.ajax("form", {
		type: "get",
		dataType: "json",
		success: function(listArr) {
			for (var i = 0; i < listArr.length; i++) {
				var tr = $("<tr></tr>");
				var th = $("<th><input type='checkbox' class='itemCheckbox'></th>");
				var th1 = $("<th>" + listArr[i].id + "</th>");
				var th2 = $("<th>" + listArr[i].name + "</th>");
				var th3 = $("<th>" + listArr[i].price + "</th>");
				var th4 = $("<th>" + listArr[i].date + "</th>");
				var th5 = $("<th><input type='checkbox' disabled " + (listArr[i].status === 1 ? 'checked' : '') + "></th>");
				var th6 = $("<th><button class='btnDelete'>删除</button> <button class='btnUpdate'>修改</button> <button class='btnDetails'>详情</button></th>");
				tr.append(th);
				tr.append(th1);
				tr.append(th2);
				tr.append(th3);
				tr.append(th4);
				tr.append(th5);
				tr.append(th6);
				$("#productTableBody").append(tr);
			}
		}
	});
	$(document).on("click", ".btnDelete", function() {
		var id = $(this).closest("tr").find("th:eq(1)").text();
		var row = $(this).closest("tr");

		console.log("商品ID: " + id);

		$.ajax({
			url: "delete",
			type: "POST",
			data: { id: id },
			dataType: "json",
			success: function(data) {
				console.log(data);
				if (data.success === true) {
					alert("删除成功");
					row.remove();
				} else {
					alert("删除失败: " + data.message);
				}
			},
			error: function() {
				alert("请求失败，请稍后重试");
			}
		});
	});


	// 添加商品
	function addProduct() {
		var productId = $("#id").val();
		var productName = $("#name").val();
		var productPrice = $("#price").val();
		var productYear = $("#year").val();
		var productMonth = $("#month").val().padStart(2, '0');
		var productDay = $("#day").val().padStart(2, '0');
		var productDate = productYear + "-" + productMonth + "-" + productDay;
		var isOffShelf = $("input[name='off-shelf']:checked").val();

		var data = {
			id: productId,
			name: productName,
			price: productPrice,
			date: productDate,
			status: isOffShelf === 'yes' ? 1 : 0
		};

		$.ajax({
			url: "insert", // 插入商品的请求 URL
			type: "POST",
			dataType: "json",
			data: data,
			success: function(response) {
				if (response.code === 200) {
					var newRow = "<tr>" +
							"<th><input type='checkbox' class='itemCheckbox'></th>" +
							"<th>" + productId + "</th>" +
							"<th>" + productName + "</th>" +
							"<th>" + productPrice + "</th>" +
							"<th>" + productDate + "</th>" +
							"<th><input type='checkbox' " + (isOffShelf === 'yes' ? 'checked' : '') + "></th>" +
							"<th><button class='btnDelete'>删除</button> <button class='btnUpdate'>修改</button> <button class='btnDetails'>详情</button></th>" +
							"</tr>";
					$("#productTableBody").append(newRow);
					$("#addProductForm")[0].reset();
				} else {
					alert("添加失败");
				}
			},
			error: function() {
				alert("请求失败");
			}
		});
	}

	// 修改商品

	// 处理按钮点击事件
	$("#btnAdd").click(function() {
		addProduct(); // 添加商品
	});

	$(document).on("click", ".btnUpdate", function() {
		$(".form-div").text("商品修改");
		$("#btnAdd").hide();
		$("#btnSave").show();

		var tdNode = $(this).closest("tr");
		console.log(tdNode.find("th"))
		tdNode.find("th").each(function (index) {
			switch (index) {
				case 1:
					$("#id").val($(this).text());
					break;
				case 2:
					$("#name").val($(this).text());
					break;
				case 3:
					$("#price").val($(this).text());
					break;
				case 4:
					var dateParts = $(this).text().split("-");
					$("#year").val(dateParts[0]);
					$("#month").val(dateParts[1]);
					$("#day").val(dateParts[2]);
					break;
				case 5:
					var isOffShelfChecked = $(this).find("input[type='checkbox']").is(":checked");
					$("input[name='off-shelf'][value='" + (isOffShelfChecked ? "yes" : "no") + "']")
							.prop("checked", true);
					break;
			}
		});

		$("#btnSave").data("editingRow", tdNode);
	});

	// 保存修改按钮点击事件
	$("#btnSave").click(function() {
		updateProduct(); // 更新商品
	});
	function updateProduct() {
		var productId = $("#id").val();
		var productName = $("#name").val();
		var productPrice = $("#price").val();
		var productYear = $("#year").val();
		var productMonth = $("#month").val().padStart(2, '0');
		var productDay = $("#day").val().padStart(2, '0');
		var productDate = productYear + "-" + productMonth + "-" + productDay;
		var isOffShelf = $("input[name='off-shelf']:checked").val();
		console.log("data=="+data)
		var data = {
			id: productId,
			name: productName,
			price: productPrice,
			date: productDate,
			status: isOffShelf === 'yes' ? 1 : 0
		};

		$.ajax({
			url: "update", // 更新商品的请求 URL
			type: "POST",
			data: data,
			success: function(response) {
				if (response.code === 200) {
					var editingRow = $("#btnSave").data("editingRow");
					editingRow.find("th").eq(1).text(productId);
					editingRow.find("th").eq(2).text(productName);
					editingRow.find("th").eq(3).text(productPrice);
					editingRow.find("th").eq(4).text(productDate);
					editingRow.find("th").eq(5).find("input[type='checkbox']").prop("checked", isOffShelf === "yes");

					$("#btnAdd").show();
					$("#btnSave").hide();
					$(".form-div").text("商品添加");
					$("#addProductForm")[0].reset();
					$("#btnSave").removeData("editingRow");
				} else {
					alert("更新失败");
				}
			},
			error: function() {
				alert("请求失败");
			}
		});
	}
	//详情
	$(document).on("click", ".btnDetails", function() {
		alert(1)
		$(".form-div").text("商品详细");
		$("#btnAdd").text("商品详细").prop("disabled", true);
		var tdNode = $(this).closest("tr");
		console.log(tdNode.find("th"))
		tdNode.find("th").each(function (index) {
			switch (index) {
				case 1:
					$("#id").val($(this).text());
					break;
				case 2:
					$("#name").val($(this).text());
					break;
				case 3:
					$("#price").val($(this).text());
					break;
				case 4:
					var dateParts = $(this).text().split("-");
					$("#year").val(dateParts[0]);
					$("#month").val(dateParts[1]);
					$("#day").val(dateParts[2]);
					break;
				case 5:
					var isOffShelfChecked = $(this).find("input[type='checkbox']").is(":checked");
					$("input[name='off-shelf'][value='" + (isOffShelfChecked ? "yes" : "no") + "']")
							.prop("checked", true);
					break;
			}
		});

		// 详情模式下禁用所有表单字段
		$("#addProductForm").find("input, select").prop("readonly", true).prop("disabled", true);

		// 显示关闭详情模式的按钮
		$("#btnCloseDetails").show();
	});
	// 关闭详情模式的按钮事件
	$("#btnCloseDetails").click(function() {
		// 恢复添加按钮的文字和功能
		$("#btnAdd").text("添加").prop("disabled", false);

		// 恢复表单字段的可编辑状态
		$("#addProductForm").find("input, select").prop("readonly", false).prop("disabled", false);

		// 清空表单
		$("#addProductForm")[0].reset();

		// 隐藏关闭详情按钮
		$(this).hide();
	});

	// 双击表单重置为添加模式
	$(".form-container").dblclick(function() {
		$(".form-div").text("商品添加");
		$("#btnAdd").show();
		$("#btnSave").hide();
		$("#addProductForm")[0].reset();
	});
</script>
</body>
</html>
